#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import requests
import json

class UpdateContentDebugger:
    def __init__(self, base_url="http://localhost:8080/api"):
        self.base_url = base_url
        self.session = requests.Session()
        self.access_token = None
        
    def get_token(self):
        """获取登录token"""
        url = f"{self.base_url}/auth/login"
        data = {
            "usernameOrEmail": "admin2",
            "password": "123456"
        }
        
        response = self.session.post(url, json=data)
        if response.status_code == 200:
            result = response.json()
            if result.get('success'):
                self.access_token = result['data']['token']
                print(f"✅ 登录成功")
                return True
        
        print(f"❌ 登录失败: {response.text}")
        return False
    
    def get_content_detail(self, content_id):
        """获取内容详情"""
        url = f"{self.base_url}/contents/{content_id}"
        headers = {'Authorization': f'Bearer {self.access_token}'}
        
        response = self.session.get(url, headers=headers)
        if response.status_code == 200:
            result = response.json()
            if result.get('success'):
                return result['data']
        return None
    
    def test_update_content(self, content_id):
        """测试更新内容接口"""
        print(f"\n🔍 测试更新内容 ID: {content_id}")
        
        # 先获取当前内容详情
        current_data = self.get_content_detail(content_id)
        if not current_data:
            print("❌ 无法获取内容详情")
            return
        
        print(f"当前内容信息:")
        print(f"  - 标题: {current_data.get('title')}")
        print(f"  - 描述: {current_data.get('description')}")
        print(f"  - 类型: {current_data.get('type')}")
        print(f"  - 标签: {current_data.get('tags')}")
        print(f"  - 发布状态: {current_data.get('published')}")
        
        url = f"{self.base_url}/contents/{content_id}"
        headers = {
            'Authorization': f'Bearer {self.access_token}',
            'Content-Type': 'application/json'
        }
        
        # 根据ContentRequest验证规则，type是必填的且不能为空
        # 但在更新时，我们不应该发送type字段，因为它是不允许修改的
        
        # 测试1：仅更新允许修改的字段
        print("\n测试1：仅更新允许修改的字段")
        update_data = {
            "title": "调试更新标题 - 测试1",
            "description": "调试更新描述 - 测试1",
            "tags": "调试,更新,测试1",
            "published": True
        }
        
        try:
            response = self.session.put(url, json=update_data, headers=headers)
            print(f"  状态码: {response.status_code}")
            if response.status_code == 200:
                result = response.json()
                if result.get('success'):
                    print(f"  ✅ 更新成功")
                    return True
                else:
                    print(f"  ❌ 业务失败: {result.get('message')}")
            else:
                print(f"  ❌ HTTP错误: {response.text}")
        except Exception as e:
            print(f"  ❌ 请求异常: {str(e)}")
        
        # 测试2：包含原始type字段
        print("\n测试2：包含原始type字段")
        update_data_with_type = {
            "title": "调试更新标题 - 测试2",
            "description": "调试更新描述 - 测试2", 
            "type": current_data.get('type'),  # 使用原始type
            "tags": "调试,更新,测试2",
            "published": False
        }
        
        try:
            response = self.session.put(url, json=update_data_with_type, headers=headers)
            print(f"  状态码: {response.status_code}")
            if response.status_code == 200:
                result = response.json()
                if result.get('success'):
                    print(f"  ✅ 更新成功")
                    return True
                else:
                    print(f"  ❌ 业务失败: {result.get('message')}")
            else:
                print(f"  ❌ HTTP错误: {response.text}")
        except Exception as e:
            print(f"  ❌ 请求异常: {str(e)}")
        
        # 测试3：最小字段更新
        print("\n测试3：仅更新标题")
        minimal_update = {
            "title": "最小更新测试"
        }
        
        try:
            response = self.session.put(url, json=minimal_update, headers=headers)
            print(f"  状态码: {response.status_code}")
            if response.status_code == 200:
                result = response.json()
                if result.get('success'):
                    print(f"  ✅ 更新成功")
                    return True
                else:
                    print(f"  ❌ 业务失败: {result.get('message')}")
            else:
                print(f"  ❌ HTTP错误: {response.text}")
        except Exception as e:
            print(f"  ❌ 请求异常: {str(e)}")
        
        return False
    
    def run_debug(self):
        """运行调试"""
        print("🔧 更新内容接口调试工具")
        print("=" * 50)
        
        # 1. 登录
        if not self.get_token():
            return
        
        # 2. 获取我的内容列表，找一个可以更新的内容
        print("\n🔍 获取我的内容...")
        url = f"{self.base_url}/contents/my"
        headers = {'Authorization': f'Bearer {self.access_token}'}
        
        response = self.session.get(url, params={"page": 0, "size": 10}, headers=headers)
        if response.status_code == 200:
            result = response.json()
            if result.get('success') and result['data']['content']:
                content_list = result['data']['content']
                test_content_id = content_list[0]['id']
                print(f"✅ 找到测试内容，ID: {test_content_id}")
                
                # 3. 测试更新
                self.test_update_content(test_content_id)
            else:
                print("❌ 没有找到可测试的内容")
        else:
            print(f"❌ 获取内容列表失败: {response.text}")

if __name__ == "__main__":
    debugger = UpdateContentDebugger()
    debugger.run_debug() 